package com.bsoft.gol.hbs.service.impl.banner;

import com.bsoft.gol.hbs.dao.ProductBannerDAO;
import com.bsoft.gol.hbs.utils.Common;
import com.bsoft.gol.hbs.utils.CommonUtils;
import ctd.controller.exception.ControllerException;
import ctd.mvc.upload.FileMetaEntity;
import ctd.mvc.upload.FileRegistry;
import ctd.mvc.upload.FileService;
import ctd.mvc.upload.exception.FileRegistryException;
import ctd.spring.boot.annotation.SsdevService;
import ctd.util.BeanUtils;
import ctd.util.annotation.RpcService;
import hcn.base.ProductBanner;
import hcn.service.base.IProductBannerService;
import hcn.sync.core.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: lanyu
 * @Description: 广告管理service
 * @Date: create in 2022/8/5 10:31
 */
@SsdevService(auth = false, value = "productBanner")
public class ProductBannerService implements IProductBannerService {
    private final static Logger log = LoggerFactory.getLogger(ProductBannerService.class);
    @Autowired
    private ProductBannerDAO productBannerDAO;
    @Resource
    private FileRegistry fileRegistry;

    /**
     * 产品广告列表
     *
     * @return
     * @throws ControllerException
     */
    @Override
    @RpcService
    public List<Map<String, Object>> queryProductBannerInfo(String tenantPId, String bannerPostion) throws ControllerException {
        List<Map<String, Object>> datas = productBannerDAO.queryProductBannerInfo(tenantPId, bannerPostion);
        Map<String, String> mapDic = new HashMap<String, String>();
        mapDic.put("position", "hcn.base.dictionary.HCN_bannerPostion");//位置
        mapDic.put("linkType", "hcn.base.dictionary.HCN_hyperLink");//链接类型
        mapDic.put("defaultFlag", "hcn.base.dictionary.HCN_yesAndNoType");//默认标志
        for (Map<String, Object> data : datas) {
            Common.mapPutKeyValue(data, mapDic);
        }
        return datas;
    }

    /**
     * 产品广告列表-按产品查询
     *
     * @return
     * @throws ControllerException
     */
    @Override
    @RpcService
    public List<ProductBanner> queryProductBannerInfoByTenantPId(int tenantPId) throws ControllerException {
        List<ProductBanner> datas = productBannerDAO.queryProductBannerInfoByTenantPId(tenantPId);
        return datas;
    }

    /**
     * 产品广告信息-根据产品广告Id明细信息
     *
     * @param id
     * @return
     * @throws ControllerException
     */
    @Override
    @RpcService
    public ProductBanner getProductBannerDetailById(int id) throws ControllerException {
        return productBannerDAO.getProductBannerDetailById(id);
    }

    /**
     * 产品广告-保存
     *
     * @param productBanner
     * @return
     * @throws ControllerException
     */
    @Override
    @RpcService
    public int add(ProductBanner productBanner) throws ControllerException {
        validateProductBanner(true, productBanner);
        productBanner.setCreateDt(new Date());
        ProductBanner object_save = productBannerDAO.save(productBanner);
        return object_save.getId();
    }

    private void validateProductBanner(boolean addOp,ProductBanner productBanner) throws ControllerException{
        String name = productBanner.getName();
        String address = productBanner.getLinkAddress();
        String prodoctDesc = productBanner.getDescription();
        if(StringUtils.isEmpty(name)){
            throw new ControllerException("广告标题为空！");
        }
//    	if(StringUtils.isEmpty(prodoctDesc)){
//    		throw new ControllerException("广告描述为空！");
//    	}
        if(name.length() > 100){
            throw new ControllerException("广告标题长度超过100的上限为空！");
        }
        if(!StringUtils.isEmpty(address) && address.length() > 500){
            throw new ControllerException("广告链接地址长度超过100的上限为空！");
        }
        if(!StringUtils.isEmpty(prodoctDesc) && prodoctDesc.length() > 200){
            throw new ControllerException("广告描述长度超过200的上限为空！");
        }
        if(!addOp){//修改
            if(productBanner.getTenantPId() == 0){
                throw new ControllerException("广告ID没有传入有效值！");
            }
        }
    }

    /**
     * 产品广告-修改
     *
     * @param productBanner
     * @return
     * @throws ControllerException
     */
    @Override
    @RpcService
    public void update(ProductBanner productBanner) throws ControllerException {
        validateProductBanner(false, productBanner);
        ProductBanner des = productBannerDAO.get(productBanner.getId());
        productBanner.setClicks(des.getClicks());
        if (null != des) {
            BeanUtils.copy(productBanner, des);
        }
        des.setLastModify(new Date());
        productBannerDAO.update(des);
    }

    /**
     * 产品广告-逻辑删除
     *
     * @param id
     * @throws ControllerException
     */
    @Override
    @RpcService
    public void delete(int id) throws ControllerException {
        productBannerDAO.delete(id);
    }

    /**
     * 产品广告-增加广告点击统计次数
     *
     * @param id
     * @throws ControllerException
     */
    @Override
    @RpcService
    public void countClicks(int id) throws ControllerException {
        productBannerDAO.updateClick(id);
    }

    /**
     * 产品广告-置顶
     *
     * @param id
     * @throws ControllerException
     */
    @Override
    @Transactional
    @RpcService
    public void updateTop(int id) throws ControllerException {
        ProductBanner productBanner = productBannerDAO.get(id);
        if (productBanner != null) {
            //更新小于本条排序号的排序号+1
            productBannerDAO.updateTop
                    (productBanner.getTenantPId(), productBanner.getPosition(), productBanner.getOrderNo());
            //更新本条排序号为1
            productBannerDAO.update(id);
        }
    }

    /**
     * 动态获取产品广告
     *
     * @param tenantPCode
     * @param position
     * @throws ControllerException
     */
    @Override
    @RpcService
    public List<Map<String, Object>> queryProductBannerList(String tenantPCode, String position) throws ControllerException {
        List<Map<String, Object>> productBannerList = productBannerDAO.queryProductBannerList(tenantPCode, position);
        if (productBannerList!=null && productBannerList.size() == 0) {
            productBannerList = productBannerDAO.queryProductBannerListDefault(tenantPCode, position);
        }
        if (CommonUtils.isNotEmpty(productBannerList)){
            for (Map<String, Object> map : productBannerList) {
                ArrayList<String> fileIds = new ArrayList<>();
                String fileId = (String)map.get("picture");
                fileIds.add(fileId);
                List<FileMetaEntity> userFileList = this.getUserFileList(fileIds);
                if (CommonUtils.isNotEmpty(userFileList)){
                    map.put("fileName",userFileList.get(0).getFileName());
                    map.put("fileSize",userFileList.get(0).getFileSize());
                    map.put("path",userFileList.get(0).getPath());
                }
            }
        }
        return productBannerList;
    }

    private List<FileMetaEntity> getUserFileList(List<String> fileIds) {
        if(CommonUtils.isNotEmpty(fileIds)){
            return fileIds.stream().map(id->{
                try {
                    return fileRegistry.load(id);
                } catch (FileRegistryException e) {
                    log.error("获取文件信息失败,{}", id);
                }
                return null;
            }).filter(CommonUtils::isNotEmpty).collect(Collectors.toList());
        }
        return Collections.emptyList();
    }
    /**
     * 获取广告连接地址
     */
    @Override
    @RpcService
    public Map<String, String> getLinkAddress(Map<String, String> map) throws ControllerException {
        String linkType = map.get("linkType");
        String linkAddress = map.get("linkAddress");
        if ("04".equals(linkType)) {
            //TODO 当链接类型为04的时候，才会调用天海获取连接地址
            //linkAddress = LifeSeaSource.getLinkAddress(linkAddress);
        }
        Map<String, String> res = new HashMap<>();
        res.put("linkAddress", linkAddress);
        res.put("linkType", linkType);
        return res;
    }
}
